package com.ht.aems.fesservice.virtualStation;

import com.ht.aems.communicate.PipeClosingListener;
import com.ht.aems.communicate.PipeListener;
import com.ht.aems.communicate.SerializablePipe;
import com.ht.aems.communicate.TcpSerializablePipe;
import com.ht.aems.fesmodel.data.*;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2010-8-7
 */
public class VirtualUCP implements PipeListener, PipeClosingListener {
    private static Logger log = Logger.getLogger(VirtualUCP.class);
    private TcpSerializablePipe pipe;

    public boolean connect() throws IOException {
        log.info("connect to fes Server");
        boolean isConnected = false;
        Socket s = new Socket("127.0.0.1", 7908);
        pipe = new TcpSerializablePipe(s);
        pipe.addPipeListener(this);
        pipe.addPipeClosingListener(this);
        isConnected = true;
        try {
            pipe.write(new CommEventConfirm());
            log.info("connect to fes server successfully!");
        } catch (IOException e) {
            log.warn(e);
            log.info("failed to connect to fes server");
            isConnected = false;
        }
        return isConnected;
    }

    public void dataUploaded(Serializable obj) {
        if (obj instanceof FesEvent) {
            FesEvent event = (FesEvent) obj;
            System.out.println(event.getMessage());
        } else if (obj instanceof YTConfirm) {
            YTConfirm confirm = (YTConfirm) obj;
            log.info("yt id: " + confirm.getYtId() + " state: " + confirm.getSuccess());
        } else if (obj instanceof YXData) {

        } else if (obj instanceof YCData) {

        }
    }

    public void pipeClosing(SerializablePipe serializablePipe) {
        System.out.println("Pipe closed.");
    }

    public static void main(String[] args) throws IOException {
        VirtualUCP ucp = new VirtualUCP();
        ucp.connect();
    }
}
